# update=1A
from machine import Pin
import json
import time
import npttime_sync
npttime_sync.sync_ntp()

import ina219xt
solar=Pin(4,Pin.OUT) #on 太阳能打开，市电断开
solars=str(solar.value())

uptime1=0
uptime2=0
#appkey='apk'

def gcy_post(volgate):   #def gcy_post(volgate,uustr):
    header={'Content-Type': 'application/x-www-form-urlencoded'}
    request_url = 'http://hn216.api.yesapi.cn/api/SVIP/Schuandi_MyApi/ACreateVol?s=SVIP.Schuandi_MyApi.ACreateVol&'+app_key    
    payload = {'volt':volgate,'elec':0}
    data = (json.dumps(payload)).encode()
    #print(data)
    r = urequests.post(request_url,data=data,headers=header)
    r.close()
    return 0

while True:
    uptime2+=1
    try:
        esp32time=int(time.localtime()[3])
        xtanpei='{:4.2f}'.format(ina219xt.read_current())
        xtvolt=float('{:4.2f}'.format(ina219xt.read_voltage()))-0.00  #修正电压
        #太阳能开关
        if xtvolt>12.25:
            solar.on()
        else:
            solar.off()
        solars=str(solar.value())
        #白天晚上处理方式
        if esp32time<9 or esp32time>19:
            if uptime2==360:
                gcy_post(str(uptime1)+' '+ str(xtvolt) +'v '+xtanpei+'a night'+ ' '+solars)
                uptime1+=1
                uptime2=0
        else:
            if uptime2>29:
                gcy_post(str(uptime1)+' '+ str(xtvolt) +'v '+xtanpei+'a day'+ ' '+solars)
                uptime1+=1
                uptime2=0      
    except Exception as ert:
        print(ert)
        pass
    time.sleep(10)
